package db;
import java.io.FileInputStream;
import java.io.InputStream;
import java.sql.Array;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;
import java.util.Properties;
import java.util.Vector;

import javax.swing.JFrame;
import javax.swing.JOptionPane;

import cn.com.action.BoolBarAction;
import cn.com.view.MainFrame;
import domain.Gdzc;
 
 
public class JDBConnection {
    public static Connection conn; // 声明Connection对象的实例
    public Statement stmt; // 声明Statement对象的实例
    public ResultSet rs; // 声明ResultSet对象的实例
    private FileInputStream inputFile;
     
    private  static String dbClassName;//定义保存数据库驱动的变量
    private static String dbUrl;
    private  static String dbUser;
    private  static String dbPwd;
    private  static JDBConnection  sqlserver;
    private int index = 0 ;
   
    /**
     * 创建sqlserver连接
     * @return
     */
    public static synchronized JDBConnection SqlServer(){
    	if(sqlserver == null){
    		 sqlserver = new JDBConnection("sqlserver.properties");
    	}
    	return sqlserver;
	}
    
    public JDBConnection(String propertyFileName) {// 带属性文件名的构造方法
        Properties prop = new Properties();// 属性集合对象
        try {
        	if(inputFile == null){
        		inputFile = new FileInputStream(propertyFileName);
        	}
            prop.load(inputFile);// 将属性文件流装载到Properties对象中
            dbClassName = prop.getProperty("dbClassName");
            dbUrl = prop.getProperty("dbUrl");
            dbUser = prop.getProperty("dbUser");
            dbPwd = prop.getProperty("dbPwd");
            Class.forName(dbClassName);// 1.注册驱动
           // conn = DriverManager.getConnection(dbUrl, dbUser, dbPwd);//2.建立与数据库的链接
        } catch (Exception e) {
            System.out.println("属性文件  " + propertyFileName + " 打开失败！");
            JOptionPane.showConfirmDialog(MainFrame.open(), "数据库连接失败！请查看当前路径下是否有（sqlserver.properties属性文件）及参数是否正确", "提示", JOptionPane.ERROR_MESSAGE);
            System.exit(0);
        }
 
           
    }
    
    public int isNo(String sql,String dataName){
    	int result=0;
    	if(sqlserver == null){
    		sqlserver =new JDBConnection();
    	}
    	try { // 捕捉异常
    		conn = getConnection(dataName);//2.建立与数据库的链接
    			if(conn == null){
    				BoolBarAction.setIndex(1);
    				return result;
    			}else{
    				BoolBarAction.setIndex(0);
    			}
    			stmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
    					ResultSet.CONCUR_READ_ONLY);
    		ResultSet count = stmt.executeQuery(sql);
    		while(count.next()){
    			result = count.getInt(1);
    		}
    	} catch (SQLException ex) {
    		System.out.println(ex.getMessage());
    		JOptionPane.showConfirmDialog(new JFrame(), ex.getMessage(), "提示", JOptionPane.ERROR_MESSAGE);
    	}finally{
    		sqlserver.close();
    	}
    	//sqlserver.close();
    	return result;
    }
    public int minID(String sql,String dataName){
    	int result=0;
    	if(sqlserver == null){
    		sqlserver =new JDBConnection();
    	}
    	   try { // 捕捉异常
    		   if(conn == null){
    			   conn = getConnection(dataName);//2.建立与数据库的链接
    		   }
    		   if(stmt == null){
    			   stmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
    					   ResultSet.CONCUR_READ_ONLY);
    		   }
           	ResultSet count = stmt.executeQuery(sql);
    			while(count.next()){
    				result = count.getInt(1);
    			}
               
           } catch (SQLException ex) {
           	System.out.println(ex.getMessage());
           	JOptionPane.showConfirmDialog(new JFrame(), ex.getMessage(), "提示", JOptionPane.ERROR_MESSAGE);
           }finally{
        	   sqlserver.close();
           }
    	return result;
    }
    /**
     * 插入数据gd_kp
     * @param startDate
     * @param endDate
     * @return
     */
    public int insterDate(List gdzcs,String dataName) {
    	int updateCount = 0;
    	if(sqlserver == null){
    		sqlserver =new JDBConnection();
    	}
    	try {
    	if(conn == null){
    		conn = getConnection(dataName);//2.建立与数据库的链接
    	}
    	if(stmt == null){
    		stmt = conn.createStatement();
    	}
    	
    	if(gdzcs.size()>0){
    		for (int i = 0; i < gdzcs.size(); i++) {
    			Gdzc gdzc=(Gdzc) gdzcs.get(i);
    			String dm=gdzc.getDm();
    			String mc=gdzc.getMc();
    			if(mc.length() > 15){
    				 mc=mc.substring(0,15);
    			}
    			String mon=gdzc.getMon();//月份
    			String bm=gdzc.getBm();//部门代码
    			String ly=gdzc.getLy();//来源
    			String dt=gdzc.getDt();//入账日期
    			String dt2=gdzc.getDt2();//启用日期
    			String yz=gdzc.getYz();//变动金额
    			String num=gdzc.getNum();//数量
    			String dw=gdzc.getDw();//单位
    			String yj_years=gdzc.getYj_years();//预计使用年限
    			String zdr=gdzc.getZdr();//录入人
    			String lrrq=gdzc.getLrrq();//录入日期
    			String remark=gdzc.getRemark();//备注
    			
    			String sql = "insert into gd_kp (dm,mc,bm,ly,dt,dt2,yz,ysyz,num,dw,yj_years,zdr,lrrq,islb,state,zj,def_str3,note)"
    				+"values('"+dm+"','"+mc+"',"+bm+",'"+ly+"','"+dt+"','"+dt2+"',"+yz+","+yz+","+num+",'"+dw+"',"+yj_years+",'"+zdr+"','"+lrrq+"',0,1,9,0,'"+remark+"')";
    			//插入一条数据
				//stmt.addBatch(sql);
				sqlserver.executeUpdate(sql,dataName);
					
    			System.out.println("插入一条数据:"+sql);
    			updateCount=i+1;
    		}
    		
			//stmt.executeBatch();//批量执行SQL语句
				
			}
    	} catch (SQLException e) {
    		try {
    			conn.rollback();
    		} catch (SQLException e1) {
    			e1.printStackTrace();
    		}
    		System.out.println(e.getMessage());
        	JOptionPane.showConfirmDialog(new JFrame(), e.getMessage(), "提示", JOptionPane.ERROR_MESSAGE);
			e.printStackTrace();
		}finally{
			sqlserver.close();
		}
    	System.out.println(updateCount);
    	return updateCount;
    }
    /**
     * 插入数据 gd_mx
     * @param startDate
     * @param endDate
     * @return
     */
    public int insterGdmx(List gdzcs,String type,String dataName) {
    	int updateCount = 0;
    	String gdyy = "2";
    	if("减少".equals(type)){
    		gdyy = "3";
    	}
    	String sqlID = "select min(id) from gd_mx";
    	int minId=sqlserver.minID(sqlID, dataName);
    	if(sqlserver == null){
    		sqlserver =new JDBConnection();
    	}
    	try {
    	if(conn == null){
    		conn = getConnection(dataName);//2.建立与数据库的链接
    	}
    	if(stmt == null){
    		stmt = conn.createStatement();
    	}
    	if(minId == 0 ){
    		minId = 1000000;
    	}
    	if(gdzcs.size()>0){
    		for (int i = 0; i < gdzcs.size(); i++) {
    			Gdzc gdzc=(Gdzc) gdzcs.get(i);
    			String dm=gdzc.getDm();
    			String mc=gdzc.getMc();
    			String mon=gdzc.getMon();//月份
    			 String bm=gdzc.getBm();//部门代码
    			 String ly=gdzc.getLy();//来源
    			 String dt=gdzc.getDt();//入账日期
    			 String dt2=gdzc.getDt2();//启用日期
    			 String yz=gdzc.getYz();//变动金额
    			 String num=gdzc.getNum();//数量
    			 String dw=gdzc.getDw();//单位
    			 String yj_years=gdzc.getYj_years();//预计使用年限
    			 String zdr=gdzc.getZdr();//录入人
    			 String lrrq=gdzc.getLrrq();//录入日期
    			 minId--;
    			String sql = "insert into gd_mx (dm,mon,bm,yy,yz,yj_years,lry,dt,shbz,id,gdyy)"
   +"values('"+dm+"',"+mon+","+bm+",'"+ly+"',"+yz+","+yj_years+",'"+zdr+"','"+lrrq+"',0,"+minId+","+gdyy+")";
    			//插入一条数据
    			System.out.println("插入一条数据:"+sql);
    			//exeSql(sql,dataName);
    			sqlserver.executeUpdate(sql,dataName);
				//stmt.addBatch(sql);
    			updateCount=i+1;
    		}
    		//stmt.executeBatch();//批量处理SQL语句
    	}
			
		} catch (SQLException e) {
			System.out.println(e.getMessage());
        	JOptionPane.showConfirmDialog(new JFrame(), e.getMessage(), "提示", JOptionPane.ERROR_MESSAGE);
        	try {
				conn.rollback();
			} catch (SQLException e1) {
				e1.printStackTrace();
			}
			e.printStackTrace();
		}finally{
			sqlserver.close();
		}
    	System.out.println(updateCount);
    	return updateCount;
    }
    
    public synchronized static void  exeSql(String sql ,String dataName){
    	sqlserver.executeUpdate(sql,dataName);
    }
    
    
    
    public JDBConnection() {// 默认的不带参数的构造函数
        try {
            Class.forName(dbClassName);// 1.注册驱动
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
 
    public synchronized static Connection getConnection(String dataName) {
      // Connection conn = null;
        try {
        	//Class.forName(dbClassName);// 1.注册驱动
            conn = DriverManager.getConnection(dbUrl+dataName+";SelectMethod=Cursor;", dbUser, dbPwd);//2.建立与数据库的链接
        } catch (Exception e) {
			e.printStackTrace();
			JOptionPane.showMessageDialog(new JFrame(), "数据库连接失败！检查账套,年度是否正确", "提示", JOptionPane.ERROR_MESSAGE);
			System.out.println(e.getMessage());
		}
           //System.exit(0);
        /**
        try {
			 Thread.sleep(50);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		**/
        return conn;
    }
    /*
     * 功能:执行更新操作
     */
    public synchronized int  executeUpdate(String sql,String dataName) {
        int result = 0; // 定义保存返回值的变量
        try { // 捕捉异常
        	if(conn == null){
        		conn = getConnection(dataName);//2.建立与数据库的链接
        		
        		//ResultSet.TYPE_SCROLL_INSENSITIVE,
				//ResultSet.CONCUR_READ_ONLY
        	}
        	if(stmt == null){
        		stmt = conn.createStatement();
        	}
        	//stmt.addBatch(sql);
            result = stmt.executeUpdate(sql); // 执行更新操作
            System.out.println(index++);
        } catch (SQLException ex) {
        	try {
				conn.rollback();
			} catch (SQLException e) {
				e.printStackTrace();
			}
        	System.out.println(ex.getMessage());
        	JOptionPane.showConfirmDialog(new JFrame(), ex.getMessage(), "提示", JOptionPane.ERROR_MESSAGE);
        }finally{
        	//sqlserver.close();
        }
        return result; // 返回保存返回值的变量
    }
 
    /*
     * 功能:关闭数据库的连接
     */
    public void close() {//6.释放资源
        try { // 捕捉异常
            try {
                if (rs != null) { // 当ResultSet对象的实例rs不为空时
                    rs.close(); // 关闭ResultSet对象
                    rs = null;
                }
            } finally {
                try {
                    if (stmt != null) { // 当Statement对象的实例stmt不为空时
                        stmt.close(); // 关闭Statement对象
                        stmt = null;
                    }
                } finally {
                    if (conn != null) { // 当Connection对象的实例conn不为空时
                        conn.close(); // 关闭Connection对象
                        conn = null;
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace(System.err); // 输出异常信息
        }
    }
 
}